package com.jiazhong.basic.pack0316.thread;

public class DemoG {
    static class ThreadLocalDemo {
        // 变量 account=0
        private ThreadLocal<Integer> account = ThreadLocal.withInitial(() -> 0);

        public void setAccount(int account) {
            this.account.set(this.account.get() + account);
        }

        public int getAccount() {
            return account.get();
        }
    }

    static class ThreadDemo extends Thread {
        private ThreadLocalDemo tld;

        public ThreadDemo(ThreadLocalDemo tld) {
            this.tld = tld;
        }

        public void run() {
            for (int i = 0; i < 10; i++) {
                tld.setAccount(1);
                System.out.println(Thread.currentThread().getName()+":"+tld.getAccount());
            }
        }
    }

    public static void main(String[] args) {
        ThreadLocalDemo tld = new ThreadLocalDemo();
        ThreadDemo t1 = new ThreadDemo(tld);
        ThreadDemo t2 = new ThreadDemo(tld);
        t1.start();
        t2.start();
    }
}
